<template>
  <div class="login-form">
    <el-form
      ref="loginFormPhone"
      :model="loginForm"
      auto-complete="on"
      label-position="left"
      label-width="30px;"
      hide-required-asterisk
    >
      <div class="title-container">
        <img :src="systemInfo.logo" height="68px" />
        <span class="title">{{ systemInfo.name }}</span>
      </div>
      <el-form-item prop="phone" verify>
        <span class="svg-container" slot="label">
          <i class="el-icon-mobile-phone"></i>
        </span>
        <el-input
          ref="phone"
          v-model.trim="loginForm.phone"
          placeholder="手机号"
          name="phone"
          type="text"
          :auto-complete="autocomplete"
        />
      </el-form-item>

      <el-form-item prop="smsCode" :verify="{ length: 6 }">
        <span class="svg-container" slot="label">
          <i class="el-icon-message"></i>
        </span>
        <el-input
          class="password-input"
          v-model.trim="loginForm.smsCode"
          placeholder="短信验证码"
        >
          <SmsButton
            slot="append"
            ref="sendcode"
            @click="sendCurrentPhoneCode()"
          />
        </el-input>
      </el-form-item>
      <div class="switch-login">
        <span @click="$emit('switch')" title="使用账号密码登录">账号登录</span>
      </div>

      <tencent-captcha
        :loading="loading"
        @adopt="handleLogin"
        :formRef="$refs.loginFormPhone"
      >
        登录
      </tencent-captcha>
    </el-form>
  </div>
</template>
<script>
import tencentCaptcha from './tencent-captcha.vue'
import SmsButton from '@/components/SmsButton'
import store from '@/store'
import { mapGetters } from 'vuex'

export default {
  name: 'phone-login',
  props: ['silent'],
  inject: ['loginSuccess'],
  components: { tencentCaptcha, SmsButton },
  data () {
    return {
      loginForm: {
        phone: '',
        smsCode: '',
        source: 'pc'
      },
      loading: false,
      redirect: undefined,
      otherQuery: {},
      autocomplete:
        import.meta.env.MODE === 'development' ? 'on' : 'new-password'
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  computed: {
    ...mapGetters(['systemInfo'])
  },
  mounted () {
    if (this.loginForm.account === '') {
      this.$refs.account.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    sendCurrentPhoneCode () {
      this.$refs.loginFormPhone.validateField('phone', phoneError => {
        //验证手机号码是否正确
        if (phoneError) {
          this.$swal.error('请输入正确的手机号')
        } else {
          this.$refs.sendcode.loading = true
          this.$POST('sot-admin-api/sys/sms/sendPhoneCode', {
            phone: this.loginForm.phone,
            type: 'sys_phone_login'
          })
            .then(res => {
              this.$refs.sendcode.loading = false
              if (res.errorCode == '00000') {
                this.$refs.sendcode.send() // 已发送
              } else {
                this.$swal.error(res.message)
              }
            })
            .catch(_ => {
              this.$refs.sendcode.loading = false
            })
        }
      })
    },
    handleLogin (res) {
      if (res) {
        this.loginForm.ticket = res.ticket
        this.loginForm.randStr = res.randstr
      }
      this.$refs.loginFormPhone.validate(valid => {
        if (valid) {
          this.loading = true
          const loginUrl = 'user/phoneLogin'
          store
            .dispatch(loginUrl, this.loginForm)
            .then(res => {
              if (res.data) {
                if (res.errorCode == '00000') {
                  if (this.silent != undefined) {
                    this.$swal.success('登录成功')
                    this.loginSuccess() // 触发父组件登录成功
                  } else {
                    this.$router.push({
                      path: this.redirect || '/',
                      query: this.otherQuery
                    })
                  }
                  return
                }

                if (res.errorCode == '00132') {
                  this.$swal.error(res.message)
                  // this.$refs.changPwd.handleChangePwd(res.data.token)
                }
              } else {
                this.$swal.error('获取用户信息失败')
              }
              // $refs.changPwd.changePwd()
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>
